<template>
  <div class="product-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>商品总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.totalProducts }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.productTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.productTrend) }}%
                <el-icon>
                  <component :is="statistics.productTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>在售商品</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.onSaleProducts }}</div>
            <div class="percentage">
              占比 {{ statistics.onSalePercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>库存预警</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount warning">{{ statistics.lowStockProducts }}</div>
            <div class="percentage">
              占比 {{ statistics.lowStockPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月销量</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.monthlySales }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.salesTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.salesTrend) }}%
                <el-icon>
                  <component :is="statistics.salesTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品分类管理 -->
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <span>商品分类</span>
          <el-button type="primary" @click="handleAddCategory">添加分类</el-button>
        </div>
      </template>
      <el-table
        :data="categoryList"
        border
        row-key="id"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column prop="name" label="分类名称" min-width="200" />
        <el-table-column prop="code" label="分类编码" width="120" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
              {{ row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productCount" label="商品数量" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditCategory(row)">
              编辑
            </el-button>
            <el-button type="success" link @click="handleAddSubCategory(row)">
              添加子分类
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDeleteCategory(row)"
              :disabled="row.productCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 商品列表 -->
    <el-card class="product-card">
      <template #header>
        <div class="card-header">
          <div class="search-form">
            <el-form :model="searchForm" inline>
              <el-form-item label="商品分类">
                <el-cascader
                  v-model="searchForm.categoryId"
                  :options="categoryOptions"
                  :props="{ checkStrictly: true }"
                  clearable
                  placeholder="请选择分类"
                />
              </el-form-item>
              <el-form-item label="商品状态">
                <el-select v-model="searchForm.status" placeholder="请选择" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="在售" value="on_sale" />
                  <el-option label="下架" value="off_sale" />
                  <el-option label="售罄" value="sold_out" />
                </el-select>
              </el-form-item>
              <el-form-item label="库存状态">
                <el-select v-model="searchForm.stockStatus" placeholder="请选择" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="充足" value="sufficient" />
                  <el-option label="预警" value="warning" />
                  <el-option label="缺货" value="out_of_stock" />
                </el-select>
              </el-form-item>
              <el-form-item label="关键词">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="商品名称/编码"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="handleAddProduct">添加商品</el-button>
            <el-button type="success" @click="handleImport">导入商品</el-button>
            <el-button type="warning" @click="handleExport">导出商品</el-button>
            <el-button type="info" @click="handleStockManage">库存管理</el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedProducts.length"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="productList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品信息" min-width="300">
          <template #default="{ row }">
            <div class="product-info">
              <el-image 
                :src="row.image" 
                :preview-src-list="[row.image]"
                fit="cover"
                class="product-image"
              />
              <div class="product-detail">
                <div class="product-name">{{ row.name }}</div>
                <div class="product-code">编码：{{ row.code }}</div>
                <div class="product-category">{{ row.categoryName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="售价" width="120">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="120">
          <template #default="{ row }">
            <span :class="{ 'warning': row.stock <= row.stockWarning }">
              {{ row.stock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销量" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditProduct(row)">
              编辑
            </el-button>
            <el-button 
              type="success" 
              link 
              @click="handleUpdateStock(row)"
            >
              库存
            </el-button>
            <el-button 
              :type="row.status === 'on_sale' ? 'warning' : 'success'"
              link 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'on_sale' ? '下架' : '上架' }}
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDeleteProduct(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 分类表单对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="categoryForm.id ? '编辑分类' : '添加分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryFormRules"
        label-width="100px"
      >
        <el-form-item label="上级分类">
          <el-cascader
            v-model="categoryForm.parentId"
            :options="categoryOptions"
            :props="{ checkStrictly: true }"
            clearable
            placeholder="请选择上级分类"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="categoryForm.code" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryForm.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCategorySubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商品表单对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      :title="productForm.id ? '编辑商品' : '添加商品'"
      width="1000px"
    >
      <el-steps :active="activeStep" finish-status="success" class="form-steps">
        <el-step title="基本信息" />
        <el-step title="规格设置" />
        <el-step title="商品详情" />
      </el-steps>

      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productFormRules"
        label-width="100px"
      >
        <!-- 基本信息 -->
        <div v-show="activeStep === 0">
          <el-form-item label="商品分类" prop="categoryId">
            <el-cascader
              v-model="productForm.categoryId"
              :options="categoryOptions"
              :props="{ checkStrictly: true }"
              placeholder="请选择商品分类"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productForm.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品编码" prop="code">
            <el-input v-model="productForm.code" placeholder="请输入商品编码" />
          </el-form-item>
          <el-form-item label="商品图片" prop="images">
            <el-upload
              v-model:file-list="fileList"
              :action="uploadUrl"
              list-type="picture-card"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :limit="10"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="previewVisible">
              <img w-full :src="previewUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品标签" prop="tags">
            <el-select
              v-model="productForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入标签"
            >
              <el-option
                v-for="tag in tagOptions"
                :key="tag.value"
                :label="tag.label"
                :value="tag.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="productForm.status">
              <el-radio label="on_sale">上架</el-radio>
              <el-radio label="off_sale">下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!-- 规格设置 -->
        <div v-show="activeStep === 1">
          <div class="spec-header">
            <el-button type="primary" @click="handleAddSpec">添加规格</el-button>
            <el-button type="success" @click="handleGenerateCombinations" :disabled="!specList.length">
              生成规格组合
            </el-button>
          </div>

          <!-- 规格定义 -->
          <div class="spec-list">
            <div v-for="(spec, specIndex) in specList" :key="specIndex" class="spec-item">
              <el-input v-model="spec.name" placeholder="规格名称" class="spec-name" />
              <div class="spec-values">
                <el-tag
                  v-for="(value, valueIndex) in spec.values"
                  :key="valueIndex"
                  closable
                  @close="handleRemoveSpecValue(specIndex, valueIndex)"
                >
                  {{ value }}
                </el-tag>
                <el-input
                  v-if="spec.inputVisible"
                  ref="specValueInputRef"
                  v-model="spec.inputValue"
                  class="spec-value-input"
                  size="small"
                  @keyup.enter="handleSpecValueConfirm(specIndex)"
                  @blur="handleSpecValueConfirm(specIndex)"
                />
                <el-button v-else class="button-new-tag" size="small" @click="handleShowSpecValueInput(specIndex)">
                  + 添加规格值
                </el-button>
              </div>
              <el-button type="danger" link @click="handleRemoveSpec(specIndex)">删除规格</el-button>
            </div>
          </div>

          <!-- 规格组合 -->
          <div v-if="specCombinations.length" class="spec-combinations">
            <h3>规格组合</h3>
            <el-table :data="specCombinations" border style="width: 100%">
              <el-table-column label="规格组合" min-width="200">
                <template #default="{ row }">
                  <div class="combination-tags">
                    <el-tag
                      v-for="(value, index) in row.values"
                      :key="index"
                      class="combination-tag"
                    >
                      {{ value }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品编码" width="180">
                <template #default="{ row }">
                  <el-input v-model="row.code" placeholder="请输入编码" />
                </template>
              </el-table-column>
              <el-table-column label="售价" width="180">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.price"
                    :min="0"
                    :precision="2"
                    :step="0.01"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="库存" width="180">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.stock"
                    :min="0"
                    :precision="0"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="预警值" width="180">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.stockWarning"
                    :min="0"
                    :precision="0"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 商品详情 -->
        <div v-show="activeStep === 2">
          <el-form-item label="商品描述" prop="description">
            <el-input
              v-model="productForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入商品描述"
            />
          </el-form-item>
          <el-form-item label="商品详情" prop="detail">
            <el-upload
              v-model:file-list="detailFileList"
              :action="uploadUrl"
              list-type="picture-card"
              :on-success="handleDetailUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleDetailRemove"
              :on-exceed="handleDetailExceed"
              :limit="20"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品参数" prop="params">
            <div v-for="(param, index) in productForm.params" :key="index" class="param-item">
              <el-input v-model="param.name" placeholder="参数名" class="param-name" />
              <el-input v-model="param.value" placeholder="参数值" class="param-value" />
              <el-button type="danger" link @click="handleRemoveParam(index)">删除</el-button>
            </div>
            <el-button type="primary" link @click="handleAddParam">添加参数</el-button>
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button v-if="activeStep > 0" @click="activeStep--">上一步</el-button>
          <el-button
            v-if="activeStep < 2"
            type="primary"
            @click="handleNextStep"
          >
            下一步
          </el-button>
          <el-button
            v-else
            type="primary"
            @click="handleProductSubmit"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 库存调整对话框 -->
    <el-dialog
      v-model="stockDialogVisible"
      title="调整库存"
      width="500px"
    >
      <el-form
        ref="stockFormRef"
        :model="stockForm"
        :rules="stockFormRules"
        label-width="100px"
      >
        <el-form-item label="当前库存">
          <span>{{ currentProduct?.stock }}</span>
        </el-form-item>
        <el-form-item label="调整方式" prop="type">
          <el-radio-group v-model="stockForm.type">
            <el-radio label="increase">增加</el-radio>
            <el-radio label="decrease">减少</el-radio>
            <el-radio label="set">直接设置</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量" prop="quantity">
          <el-input-number
            v-model="stockForm.quantity"
            :min="0"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-input
            v-model="stockForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调整原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStockSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown, Plus } from '@element-plus/icons-vue'
import {
  getMerchantProductList,
  getMerchantProductStatistics,
  createMerchantProduct,
  updateMerchantProduct,
  deleteMerchantProduct,
  batchDeleteMerchantProducts,
  updateMerchantProductStatus,
  updateMerchantProductStock,
  exportMerchantProducts,
  importMerchantProducts,
  getMerchantCareCategoryList,
  createMerchantCareCategory,
  updateMerchantCareCategory,
  deleteMerchantCareCategory
} from '@/api/merchant'
import { useRouter } from 'vue-router'

// 统计数据
const statistics = reactive({
  totalProducts: 0,
  productTrend: 0,
  onSaleProducts: 0,
  onSalePercentage: 0,
  lowStockProducts: 0,
  lowStockPercentage: 0,
  monthlySales: 0,
  salesTrend: 0
})

// 分类列表
const categoryList = ref([])
const categoryOptions = ref([])

// 商品列表
const loading = ref(false)
const productList = ref([])
const selectedProducts = ref([])

// 搜索表单
const searchForm = reactive({
  categoryId: null,
  status: '',
  stockStatus: '',
  keyword: ''
})

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 分类表单
const categoryDialogVisible = ref(false)
const categoryFormRef = ref(null)
const categoryForm = reactive({
  id: '',
  parentId: null,
  name: '',
  code: '',
  sort: 0,
  status: 'enabled'
})

// 商品表单
const productDialogVisible = ref(false)
const productFormRef = ref(null)
const productForm = reactive({
  id: '',
  categoryId: null,
  name: '',
  code: '',
  image: '',
  price: 0,
  stock: 0,
  stockWarning: 10,
  status: 'off_sale',
  description: '',
  tags: [],
  params: [],
  detail: '',
  specList: [],
  specCombinations: []
})

// 库存表单
const stockDialogVisible = ref(false)
const stockFormRef = ref(null)
const stockForm = reactive({
  type: 'increase',
  quantity: 0,
  reason: ''
})
const currentProduct = ref(null)

// 上传相关
const uploadUrl = import.meta.env.VITE_API_URL + '/merchant/upload'

// 表单验证规则
const categoryFormRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const productFormRules = {
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
  image: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  stockWarning: [{ required: true, message: '请输入库存预警值', trigger: 'blur' }],
  status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
  tags: [
    { type: 'array', message: '请选择商品标签', trigger: 'change' }
  ]
}

const stockFormRules = {
  type: [{ required: true, message: '请选择调整方式', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入调整数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入调整原因', trigger: 'blur' }]
}

// 表单步骤
const activeStep = ref(0)

// 规格相关
const specList = ref([])
const specCombinations = ref([])
const specValueInputRef = ref(null)

// 标签选项
const tagOptions = ref([
  { label: '新品', value: 'new' },
  { label: '热销', value: 'hot' },
  { label: '促销', value: 'promotion' },
  { label: '推荐', value: 'recommend' }
])

// 图片上传相关
const fileList = ref([])
const detailFileList = ref([])
const previewVisible = ref(false)
const previewUrl = ref('')

const router = useRouter()

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantProductStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    const { data } = await getMerchantCareCategoryList()
    categoryList.value = data
    // 转换为级联选择器需要的格式
    categoryOptions.value = formatCategoryOptions(data)
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 格式化分类选项
const formatCategoryOptions = (categories) => {
  return categories.map(category => ({
    value: category.id,
    label: category.name,
    children: category.children ? formatCategoryOptions(category.children) : undefined
  }))
}

// 获取商品列表
const getProductList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantProductList(params)
    productList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getProductList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'categoryId' ? null : ''
  })
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedProducts.value = rows
}

// 添加分类
const handleAddCategory = () => {
  Object.keys(categoryForm).forEach(key => {
    categoryForm[key] = key === 'status' ? 'enabled' : key === 'sort' ? 0 : ''
  })
  categoryForm.id = ''
  categoryDialogVisible.value = true
}

// 编辑分类
const handleEditCategory = (row) => {
  Object.assign(categoryForm, row)
  categoryDialogVisible.value = true
}

// 添加子分类
const handleAddSubCategory = (row) => {
  Object.keys(categoryForm).forEach(key => {
    categoryForm[key] = key === 'status' ? 'enabled' : key === 'sort' ? 0 : ''
  })
  categoryForm.id = ''
  categoryForm.parentId = row.id
  categoryDialogVisible.value = true
}

// 删除分类
const handleDeleteCategory = async (row) => {
  if (row.productCount > 0) {
    ElMessage.warning('该分类下存在商品，无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除该分类吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantCareCategory(row.id)
    ElMessage.success('删除成功')
    getCategoryList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
    }
  }
}

// 提交分类表单
const handleCategorySubmit = async () => {
  if (!categoryFormRef.value) return
  
  try {
    await categoryFormRef.value.validate()
    if (categoryForm.id) {
      await updateMerchantCareCategory(categoryForm.id, categoryForm)
      ElMessage.success('更新成功')
    } else {
      await createMerchantCareCategory(categoryForm)
      ElMessage.success('创建成功')
    }
    categoryDialogVisible.value = false
    getCategoryList()
  } catch (error) {
    console.error('提交分类失败:', error)
  }
}

// 添加商品
const handleAddProduct = () => {
  Object.keys(productForm).forEach(key => {
    productForm[key] = key === 'status' ? 'off_sale' : 
                      key === 'price' || key === 'stock' || key === 'stockWarning' ? 0 : ''
  })
  productForm.id = ''
  productDialogVisible.value = true
}

// 编辑商品
const handleEditProduct = (row) => {
  Object.assign(productForm, row)
  productDialogVisible.value = true
}

// 删除商品
const handleDeleteProduct = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该商品吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantProduct(row.id)
    ElMessage.success('删除成功')
    getProductList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除选中的商品吗？', '提示', {
      type: 'warning'
    })
    const ids = selectedProducts.value.map(row => row.id)
    await batchDeleteMerchantProducts(ids)
    ElMessage.success('批量删除成功')
    getProductList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 调整库存
const handleUpdateStock = (row) => {
  currentProduct.value = row
  Object.keys(stockForm).forEach(key => {
    stockForm[key] = key === 'type' ? 'increase' : ''
  })
  stockForm.quantity = 0
  stockDialogVisible.value = true
}

// 提交库存调整
const handleStockSubmit = async () => {
  if (!stockFormRef.value) return
  
  try {
    await stockFormRef.value.validate()
    const { type, quantity, reason } = stockForm
    let finalQuantity = quantity
    
    if (type === 'decrease') {
      finalQuantity = -quantity
    } else if (type === 'set') {
      finalQuantity = quantity - currentProduct.value.stock
    }
    
    await updateMerchantProductStock(currentProduct.value.id, {
      quantity: finalQuantity,
      reason
    })
    ElMessage.success('库存调整成功')
    stockDialogVisible.value = false
    getProductList()
    getStatistics()
  } catch (error) {
    console.error('调整库存失败:', error)
  }
}

// 切换商品状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'on_sale' ? 'off_sale' : 'on_sale'
    await updateMerchantProductStatus(row.id, { status: newStatus })
    ElMessage.success('状态更新成功')
    getProductList()
    getStatistics()
  } catch (error) {
    console.error('更新状态失败:', error)
  }
}

// 导入商品
const handleImport = () => {
  // TODO: 实现商品导入功能
  ElMessage.info('商品导入功能开发中')
}

// 导出商品
const handleExport = async () => {
  try {
    const params = {
      ...searchForm
    }
    await exportMerchantProducts(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 上传图片
const handleUploadSuccess = (response, uploadFile) => {
  productForm.images.push(response.data.url)
  ElMessage.success('上传成功')
}

const handleDetailUploadSuccess = (response) => {
  productForm.detail += `<img src="${response.data.url}" alt="detail image" />`
  ElMessage.success('上传成功')
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const handleRemove = (uploadFile) => {
  const index = productForm.images.indexOf(uploadFile.url)
  if (index !== -1) {
    productForm.images.splice(index, 1)
  }
}

const handleDetailRemove = (uploadFile) => {
  const imgTag = `<img src="${uploadFile.url}" alt="detail image" />`
  productForm.detail = productForm.detail.replace(imgTag, '')
}

const handlePictureCardPreview = (uploadFile) => {
  previewUrl.value = uploadFile.url
  previewVisible.value = true
}

const handleExceed = () => {
  ElMessage.warning('最多上传10张商品图片')
}

const handleDetailExceed = () => {
  ElMessage.warning('最多上传20张详情图片')
}

// 下一步
const handleNextStep = async () => {
  if (activeStep.value === 0) {
    try {
      await productFormRef.value.validateField(['categoryId', 'name', 'code', 'images'])
      activeStep.value++
    } catch (error) {
      return
    }
  } else if (activeStep.value === 1) {
    if (!specList.value.length || !specCombinations.value.length) {
      ElMessage.warning('请至少添加一个规格组合')
      return
    }
    activeStep.value++
  }
}

// 提交商品表单
const handleProductSubmit = async () => {
  if (!productFormRef.value) return
  
  try {
    await productFormRef.value.validate()
    
    // 处理规格数据
    productForm.specList = specList.value.map(spec => ({
      name: spec.name,
      values: spec.values
    }))
    productForm.specCombinations = specCombinations.value

    if (productForm.id) {
      await updateMerchantProduct(productForm.id, productForm)
      ElMessage.success('更新成功')
    } else {
      await createMerchantProduct(productForm)
      ElMessage.success('创建成功')
    }
    productDialogVisible.value = false
    getProductList()
    getStatistics()
  } catch (error) {
    console.error('提交商品失败:', error)
  }
}

// 添加规格
const handleAddSpec = () => {
  specList.value.push({
    name: '',
    values: [],
    inputVisible: false,
    inputValue: ''
  })
}

// 删除规格
const handleRemoveSpec = (index) => {
  specList.value.splice(index, 1)
  handleGenerateCombinations()
}

// 显示规格值输入框
const handleShowSpecValueInput = (specIndex) => {
  specList.value[specIndex].inputVisible = true
  nextTick(() => {
    specValueInputRef.value?.focus()
  })
}

// 确认规格值
const handleSpecValueConfirm = (specIndex) => {
  const spec = specList.value[specIndex]
  if (spec.inputValue) {
    if (!spec.values.includes(spec.inputValue)) {
      spec.values.push(spec.inputValue)
    }
  }
  spec.inputVisible = false
  spec.inputValue = ''
  handleGenerateCombinations()
}

// 删除规格值
const handleRemoveSpecValue = (specIndex, valueIndex) => {
  specList.value[specIndex].values.splice(valueIndex, 1)
  handleGenerateCombinations()
}

// 生成规格组合
const handleGenerateCombinations = () => {
  const validSpecs = specList.value.filter(spec => spec.name && spec.values.length > 0)
  if (!validSpecs.length) {
    specCombinations.value = []
    return
  }

  const generateCombinations = (specs, current = [], index = 0) => {
    if (index === specs.length) {
      return [current]
    }

    const combinations = []
    const spec = specs[index]
    for (const value of spec.values) {
      combinations.push(...generateCombinations(specs, [...current, value], index + 1))
    }
    return combinations
  }

  const combinations = generateCombinations(validSpecs)
  specCombinations.value = combinations.map(values => ({
    values,
    code: '',
    price: productForm.price || 0,
    stock: productForm.stock || 0,
    stockWarning: productForm.stockWarning || 10
  }))
}

// 添加参数
const handleAddParam = () => {
  productForm.params.push({ name: '', value: '' })
}

// 删除参数
const handleRemoveParam = (index) => {
  productForm.params.splice(index, 1)
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getProductList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getProductList()
}

// 库存管理
const handleStockManage = () => {
  router.push('/merchant/product/stock')
}

onMounted(() => {
  getStatistics()
  getCategoryList()
  getProductList()
})
</script>

<style lang="scss" scoped>
.product-management {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 10px;

        &.warning {
          color: #e6a23c;
        }
      }

      .trend {
        font-size: 14px;
        color: #909399;

        .up {
          color: #67c23a;
        }

        .down {
          color: #f56c6c;
        }
      }

      .percentage {
        font-size: 14px;
        color: #909399;
      }
    }
  }

  .category-card,
  .product-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .search-form {
        flex: 1;
        margin-right: 20px;
      }

      .action-buttons {
        display: flex;
        gap: 10px;
      }
    }
  }

  .product-info {
    display: flex;
    align-items: center;

    .product-image {
      width: 60px;
      height: 60px;
      margin-right: 10px;
      border-radius: 4px;
    }

    .product-detail {
      .product-name {
        font-weight: bold;
        margin-bottom: 5px;
      }

      .product-code,
      .product-category {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .product-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .product-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .product-image {
      width: 100px;
      height: 100px;
      display: block;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .form-steps {
    margin-bottom: 20px;
  }

  .spec-header {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .spec-list {
    margin-bottom: 20px;

    .spec-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 15px;
      padding: 10px;
      border: 1px solid #EBEEF5;
      border-radius: 4px;

      .spec-name {
        width: 150px;
        margin-right: 15px;
      }

      .spec-values {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-right: 15px;

        .spec-value-input {
          width: 100px;
        }
      }
    }
  }

  .spec-combinations {
    margin-top: 20px;

    h3 {
      margin-bottom: 15px;
      font-size: 16px;
      font-weight: 500;
    }

    .combination-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;

      .combination-tag {
        margin-right: 5px;
      }
    }
  }

  .param-item {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;

    .param-name {
      width: 200px;
    }

    .param-value {
      flex: 1;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>